package License

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"Volta/Core/Utils/Tools"
)

//.生成秘钥
func BuildSign(license string) (string,string) {

	var password string
	var splitStr string = "JSI#^faq&*!@AJIQ.["
	var super1 string = "SIQO"
	var super2 string = "WIQ1"
	var super3 string = "O135"
	var backKey string = "FX"
	var nico string
	var sign string
	var checkSign string

	//.生成随机码
	random := strconv.Itoa(int(rand.Int31n(99999999)))
	//.生成混淆后钥匙
	nico = base64.StdEncoding.EncodeToString([]byte(splitStr + random + "]"))
	//.base64密码
	password = base64.StdEncoding.EncodeToString([]byte(license))
	//.生成签名
	sign = Tools.Md5(super3+random[4:8]+license+random[0:4]+super1+super2)
	//.服务器返回消息验签
	checkSign = Tools.Md5(sign+nico+random+backKey)
	//.验签消息组合
	license = nico + "+" + password + "+" + sign
	return license,checkSign
}
//.验证license
func CheckLicense(license string,registerAddr string) bool{
	if license == "" {
		fmt.Println("license 不可为空")
		time.Sleep(time.Second * 1000)
		return true
	}
	if len(license) != 20{
		fmt.Println("license错误，正确的license一般为SD/HD开头20位编码")
		time.Sleep(time.Second * 1000)
		return true
	}
	fmt.Println("连接注册服务器中...")
	license,checkSign := BuildSign(license)
	request,_ := http.NewRequest("GET","http://"+registerAddr+"/api/license?key="+license, nil)
	client := &http.Client{}
	response, responseErr := client.Do(request)
	if responseErr != nil {
		fmt.Println("验证服务器无法连接，请重启服务")
		time.Sleep(time.Second * 1000)
		return true
	}
	body,_ := ioutil.ReadAll(response.Body)
	bodyStr := string(body)
	if(len(bodyStr) != 32){
		fmt.Println("验证服务器无法连接，请重启服务")
		time.Sleep(time.Second * 1000)
		return true
	}
	if(bodyStr != checkSign){
		fmt.Println("注册码错误，请重启服务")
		time.Sleep(time.Second * 1000)
		return true
	}else{
		fmt.Println("登录成功，开启服务中...")
		return true
	}
	return true
}
